package com.yio.wifi;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.Bind;
import butterknife.ButterKnife;

/*
 *  @项目名：  wificonnector
 *  @包名：    com.yio.wifi
 *  @文件名:   NetworkReceiver
 *  @创建者:   yio
 *  @创建时间:  2016/9/2 8:23
 *  @描述：    wifi设置界面fragment
 */
public class WifiFragment extends Fragment implements NetworkReceiver.NetEvent {
    @Bind(R.id.lv_wifi)
    ListView mLvWifi;
    @Bind(R.id.iv_wifi_switch)
    ImageView mIvWifiSwitch;
    @Bind(R.id.btn_wifi_scan)
    Button mBtnWifiScan;
    @Bind(R.id.tv_wifi_state)
    TextView mTvWifiState;
    private WifiAdmin wifiAdmin;

    private List<ScanResult> wifiList = new ArrayList<>();
    ;//存放周围wifi热点对象的列表
    private CommAdapter<ScanResult> adapter;
    //    private static final String WPA = "通过WPA进行保护";
//    private static final String WPA2 = "通过WPA2进行保护";
//    private static final String WPAWPA2 = "通过WPA/WPA2进行保护";
//    private static final String EAP = "通过802.1x进行保护";
    public static NetworkReceiver.NetEvent event;
    private boolean mSwitchState;//wifi开启状态，false为关 true为开
    private int mConnectType;//0:未连接，1:连接成功，2:密码错误，3:连接中
    public boolean pwdVisiable = false; //wifi密码输入框可见与否 默认不可见
    private OpenWifiTask task = new OpenWifiTask();
    private ExecutorService mThreadExecutor;
    private int mCurrentNetId;
    public EditText mEditText;
    private String mWifiItemSSID;//wifi的SSID名称
    private int mLastNetId;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wifi, null);
        ButterKnife.bind(this, view);
        loadData();
        initListener();
        return view;
    }

    /**
     * 点击当前已连接的wifi条目弹出的dialog
     *
     * @param scanResult
     */
    private void showWifiDialog(final ScanResult scanResult) {
        final Dialog dialog = new Dialog(getActivity(), R.style.dialog);
        View view = LayoutInflater.from(getActivity())
                .inflate(R.layout.dialog_wifi_connected, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(view);
        dialog.show();
        TextView tvSSID = (TextView) view.findViewById(R.id.tv_dialog_ssid);
        tvSSID.setText(scanResult.SSID);
        TextView tvState = (TextView) view.findViewById(R.id.tv_dialog_state);
        tvState.setText(mConnectType == 2 ? "身份验证出现问题" : "已连接");
        RadioButton rBCancle = (RadioButton) view.findViewById(R.id.bt_dialog_cancel);
        RadioButton rBsure = (RadioButton) view.findViewById(R.id.bt_dialog_sure);
        rBCancle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int netId = 0;
                List<WifiConfiguration> configuration = wifiAdmin.getWiFiConfiguration();
                for (WifiConfiguration info : configuration) {
                    if (info.SSID.equals("\"" + scanResult.SSID + "\"")) {
                        netId = info.networkId;
                    }
                }
                wifiAdmin.removeNetwork(netId);//忘记链接错误的密码
                wifiAdmin.disConnectionWifi();
                dialog.dismiss();
            }
        });

        rBsure.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 当前已连接wifi情况下-点击已配置过密码的wifi条目弹出的dialog
     */
    private void showWifiDialog2() {
        final Dialog dialog = new Dialog(getActivity(), R.style.dialog);
        View view = LayoutInflater.from(getActivity())
                .inflate(R.layout.dialog_wifi_saved, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(view);
        dialog.show();
        TextView tvSSID = (TextView) view.findViewById(R.id.tv_dialog_ssid);
        TextView tvCancle = (TextView) view.findViewById(R.id.tv_dialog_cancle);
        RadioButton rbCancle = (RadioButton) view.findViewById(R.id.bt_dialog_cancel);
        RadioButton rbSure = (RadioButton) view.findViewById(R.id.bt_dialog_sure);
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int netId = 0;
                List<WifiConfiguration> configuration = wifiAdmin.getWiFiConfiguration();
                for (WifiConfiguration info : configuration) {
                    if (info.SSID.equals("\"" + mWifiItemSSID + "\"")) {
                        netId = info.networkId;
                    }
                }
                wifiAdmin.removeNetwork(netId);
                dialog.dismiss();
                getAllNetWorkList();
                getAdapter();
            }
        });
        rbCancle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                dialog.dismiss();
            }
        });
        rbSure.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                wifiAdmin.ConnectWifi(mCurrentNetId);
                dialog.dismiss();
            }
        });
        tvSSID.setText(mWifiItemSSID);
    }

    private Handler mHandler = new Handler();

    public void initListener() {
        //wifi开关按钮
        mIvWifiSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSwitchState = !mSwitchState;
                mIvWifiSwitch.setImageResource(mSwitchState ? R.mipmap.switch_on : R.mipmap.switch_off);
                if (mSwitchState) {
                    mTvWifiState.setText("正在打开WIFI...");
                    mTvWifiState.setVisibility(View.VISIBLE);
                    wifiAdmin.openWifi();
                } else {
                    wifiAdmin.closeWifi();
                    onCloseWifi();
                }
            }
        });
        //点击扫描周边wifi信息
        mBtnWifiScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBtnWifiScan.setEnabled(false);
                wifiList.clear();
                adapter.notifyDataSetChanged();
                mTvWifiState.setVisibility(View.VISIBLE);
                mHandler.post(new ScanTask());
                mThreadExecutor.submit(new Runnable() {
                    @Override
                    public void run() {
                        SystemClock.sleep(3000);
                        wifiAdmin.startScan();
                    }
                });
            }
        });
        //wifi列表 item 点击事件
        mLvWifi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ScanResult scanResult = wifiList.get(position);
                // 连接WiFi
                mWifiItemSSID = scanResult.SSID;
                if (mConnectType == 1 && mWifiItemSSID.equals(wifiAdmin.getSSID())) {
                    showWifiDialog(scanResult);
                    return;
                }
                L.e("scanResult.capabilities------" + scanResult.capabilities);
                if (!scanResult.capabilities.contains("WPA")) {//连接公共 无密码保护wifi
                    WifiConfiguration wifiConfiguration = wifiAdmin.createWifiInfo(mWifiItemSSID,
                            null,
                            1);
                    mCurrentNetId = wifiAdmin.addNetwork(wifiConfiguration);
                    L.e("netId:" + mCurrentNetId);
                    if (mConnectType == 1) {
                        wifiAdmin.disConnectionWifi();
                    }
                } else {//连接密码保护的wifi
                    mCurrentNetId = wifiAdmin.IsConfiguration("\"" + mWifiItemSSID + "\"");
                    if (mCurrentNetId != -1) {// 已有配置信息
                        if (mConnectType == 0) {
                            //未连接wifi点击直接连接
                            wifiAdmin.ConnectWifi(mCurrentNetId);
                        } else {
                            //已连接wifi或当前密码错误点击弹对话框 提示用户操作
                            showWifiDialog2();
                        }
                    } else {
                        // 没有配置好信息，需要进行配置 （输入密码）
                        showPasswordDialog(mWifiItemSSID);
                    }
                }
            }
        });
        int state = wifiAdmin.checkState();
        //根据wifi可用状态 设置wifi开关图片
        initWifiData(state);
    }

    /**
     * wifi打开后的回调方法
     */
    @Override
    public void onOpenWifi() {
        mSwitchState = true;
        mIvWifiSwitch.setImageResource(R.mipmap.switch_on);
        mTvWifiState.setVisibility(View.VISIBLE);
        mTvWifiState.setText("正在打开WIFI...");
        mHandler.post(task);
    }

    /**
     * wifi关闭后的回调方法
     */
    @Override
    public void onCloseWifi() {
        mSwitchState = false;
        mIvWifiSwitch.setImageResource(R.mipmap.switch_off);
        mBtnWifiScan.setEnabled(false);
        mTvWifiState.setVisibility(View.INVISIBLE);
        wifiList.clear();
        adapter.notifyDataSetChanged();
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onConnectChange(int connectType) {
        mConnectType = connectType;
        getAllNetWorkList();
        getAdapter();
    }

    /**
     * 扫描到wifi信息的回调方法
     */
    @Override
    public void onScanCompleted() {
        if (wifiList.size() != 0) {
            mBtnWifiScan.setEnabled(true);
            mHandler.removeCallbacksAndMessages(null);
            return;
        }
        wifiAdmin = new WifiAdmin(getContext());
        getAllNetWorkList();
        getAdapter();
        L.e("adapter.getCount()--" + adapter.getCount());
    }

    class OpenWifiTask
            implements Runnable {

        @Override
        public void run() {
            if (wifiList.size() != 0) {
                return;
            }
            mTvWifiState.setText("正在扫描...");
            onScanCompleted();
            mHandler.postDelayed(this, 1100);
        }

    }

    class ScanTask
            implements Runnable {

        @Override
        public void run() {
            if (wifiList.size() != 0) {
                return;
            }
            mTvWifiState.setText("正在扫描...");
            mHandler.postDelayed(this, 1100);
        }

    }

    public void loadData() {
        this.event = this;
        mThreadExecutor = Executors.newSingleThreadExecutor();
        wifiAdmin = new WifiAdmin(getActivity());
        mConnectType = wifiAdmin.isWifiConnected() ? 1 : 0;
    }

    private void initWifiData(int state) {
        if (state == WifiManager.WIFI_STATE_DISABLED) {
            mSwitchState = false;
            mBtnWifiScan.setEnabled(false);
        } else if (state == WifiManager.WIFI_STATE_ENABLED) {
            mSwitchState = true;
            getAllNetWorkList();
            getAdapter();
        }
        mIvWifiSwitch.setImageResource(mSwitchState
                ? R.mipmap.switch_on
                : R.mipmap.switch_off);
    }

    private void getAdapter() {
        if (adapter == null) {
            adapter = new CommAdapter<ScanResult>(getContext(), wifiList, R.layout.wifi_item) {

                @Override
                public void convert(CommViewHolder holder, ScanResult item) {
                    //WIFI图标设置
                    boolean isEncrypt = item.capabilities.contains("WPA2") || item.capabilities.contains(
                            "WPA");
                    holder.setImageResource(R.id.iv_wifi_icon,
                            isEncrypt
                                    ? R.mipmap.wifi_lock
                                    : R.mipmap.wifi);
                    holder.setText(R.id.tv_wifi_name, item.SSID);
                    TextView state = holder.getView(R.id.tv_wifi_state);
                    //WIFI加密信息为空 textview设置为gone
                    /*if (item.capabilities.contains("WPA")) {
                        state.setVisibility(View.VISIBLE);
                    } else {
                        state.setVisibility(View.GONE);
                    }

                    if (item.capabilities.contains("WPA2") && item.capabilities.contains("WPA")) {
                        holder.setText(R.id.tv_wifi_state, WPAWPA2);
                    } else if (item.capabilities.contains("WPA2-EAP")) {
                        holder.setText(R.id.tv_wifi_state, EAP);
                    } else if (item.capabilities.contains("WPA2") && !item.capabilities.contains(
                            "WPA")) {
                        holder.setText(R.id.tv_wifi_state, WPA2);
                    } else if (item.capabilities.contains("WPA") && !item.capabilities.contains(
                            "WPA2")) {
                        holder.setText(R.id.tv_wifi_state, WPA);
                    }*/
                    List<WifiConfiguration> configuration = wifiAdmin.getWiFiConfiguration();
                    if (configuration != null) {
                        for (int i = 0; i < configuration.size(); i++) {
                            WifiConfiguration info = configuration.get(i);
                            if (info.SSID.equals("\"" + item.SSID + "\"")) {
                                state.setVisibility(View.VISIBLE);
                                holder.setText(R.id.tv_wifi_state, "已保存");
                            }
                        }
                    }
                    if (item.SSID.equals(wifiAdmin.getSSID()) && mConnectType == 1) {
                        state.setVisibility(View.VISIBLE);
                        holder.setText(R.id.tv_wifi_state, "已连接");
                    } else if (item.SSID.equals(wifiAdmin.getSSID()) && mConnectType == 2) {
                        state.setVisibility(View.VISIBLE);
                        holder.setText(R.id.tv_wifi_state, "身份验证出现问题");
                    } else if (item.SSID.equals(wifiAdmin.getSSID()) && mConnectType == 3) {
                        state.setVisibility(View.VISIBLE);
                        holder.setText(R.id.tv_wifi_state, "连接中...");
                    } else {
                        state.setVisibility(View.GONE);
                    }
                }
            };
            mLvWifi.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取扫描到的周边wifi列表信息
     */
    public void getAllNetWorkList() {
        wifiAdmin.startScan();
        //        List<ScanResult> scanResults = sortByLevel(noSameName(this.list));
        //获取周边wifi信息 并去除同名SSID的wifi信息
        List<ScanResult> list = noSameName(wifiAdmin.getWifiList());
        //将当前连接的wifi信息放在列表第一位
        for (ScanResult scanResult : list) {
            if (scanResult.SSID.equals(wifiAdmin.getSSID())) {
                list.remove(scanResult);
                list.add(0, scanResult);
                break;
            }
        }
        wifiList.clear();
        wifiList.addAll(list);
        if (list.size() != 0) {
            mTvWifiState.setVisibility(View.INVISIBLE);
        }
    }

    /*
     * 去除同名SSID
     * */
    public List<ScanResult> noSameName(List<ScanResult> list) {
        List<ScanResult> newlist = new ArrayList<ScanResult>();
        for (ScanResult result : list) {
            if (!TextUtils.isEmpty(result.SSID) && !containName(newlist, result.SSID)) {
                newlist.add(result);
            }
        }
        return newlist;
    }

    /**
     * 判断一个扫描结果中，是否包含了某个名称的WIFI
     *
     * @param sr   扫描结果
     * @param name 要查询的名称
     * @return 返回true表示包含了该名称的WIFI，返回false表示不包含
     */
    public boolean containName(List<ScanResult> sr, String name) {
        for (ScanResult result : sr) {
            if (!TextUtils.isEmpty(result.SSID) && result.SSID.equals(name)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 按照wifi信号强度由强到弱排序
     *
     * @param list
     */
    private List<ScanResult> sortByLevel(List<ScanResult> list) {
        for (int i = 0; i < list.size(); i++) {
            for (int j = 1; j < list.size(); j++) {
                if (list.get(i).level < list.get(j).level)    //level属性即为强度
                {
                    ScanResult temp = null;
                    temp = list.get(i);
                    list.set(i, list.get(j));
                    list.set(j, temp);
                }
            }
        }
        return list;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    private void showPasswordDialog(final String SSID) {
        final Dialog dialog = new Dialog(getActivity(), R.style.dialog);
        View view = LayoutInflater.from(getActivity())
                .inflate(R.layout.dialog_wifi, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(view);
        dialog.show();
        TextView tvSSID = (TextView) view.findViewById(R.id.tv_dialog_ssid);
        tvSSID.setText(SSID);
        final EditText etPassword = (EditText) view.findViewById(R.id.et_input_password);
        final RadioButton btSure = (RadioButton) view.findViewById(R.id.bt_dialog_sure);
        RadioButton btCancle = (RadioButton) view.findViewById(R.id.bt_dialog_cancel);
        ImageView ivControllType = (ImageView) view.findViewById(R.id.iv_controll_type);
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //密码长度最低8位 少于八位确认键不可点击
                if (s.length() >= 8) {
                    btSure.setClickable(true);
                    btSure.setTextColor(Color.parseColor("#333843"));
                } else {
                    btSure.setClickable(false);
                    btSure.setTextColor(Color.parseColor("#8e9197"));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        ivControllType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pwdVisiable = !pwdVisiable;
                //改变文本显示样式 visibleType为true edittext的文本明文显示 反之 密文显示
                etPassword.setInputType(pwdVisiable
                        ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                        : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                Editable etable = etPassword.getText();
                Selection.setSelection(etable, etable.length());
            }
        });
        btSure.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String password = etPassword.getText()
                        .toString()
                        .trim();
                mCurrentNetId = wifiAdmin.addNetwork(wifiAdmin.createWifiInfo(SSID, password, 3));
                L.e("mCurrentNetId:" + mCurrentNetId + "-------mLastNetId:" + mLastNetId);
                if (mCurrentNetId != -1 && mLastNetId != 0) {
                    wifiAdmin.disConnectionWifi();
                }
                dialog.dismiss();
            }
        });

        btCancle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                dialog.dismiss();
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog2) {
                //隐藏软键盘
                InputMethodManager mm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (mm.isActive()) {
                    mm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        });
    }
}
